import router from "./router";
import store from "./store";
import { Message } from "element-ui";
import NProgress from "nprogress"; // 进度条
import "nprogress/nprogress.css"; // 进度条样式
import { getToken, setToken } from "@/utils/auth"; // 从cookie获取，设置token
import getPageTitle from "@/utils/get-page-title";
import { GetRequest } from "@/utils";

NProgress.configure({
  showSpinner: false
}); // NPROGRESS配置

//默认全权限
const _info = {
  roles: ["admin"]
};

router.beforeEach(async (to, from, next) => {
  NProgress.start();
  document.title = getPageTitle(to.meta.title);
  // 本地登录/单点登录缺省页
  if (to.path == "/index/sso/tokenSync" || to.path == "/index/sso/dev" || to.path == "/showmsg") {
    next();
  } else {
    // 获取已有token
    let hasToken = getToken();
    console.log('hasToken1', hasToken);
    // 获取URL中的参数
    let newToken = GetRequest(window.location.href).sso_user;
    console.log('newToken', newToken);
    // 如果URL中带有token参数，则重设token
    if (newToken) {
      setToken(newToken);
      hasToken = getToken()
      // 重设token后更改url为不带参数，重新进入流程
      window.location.href = process.env.VUE_APP_BASE_YMW
    } else {
      // 判断是否有token
      const hasRoles = store.getters.roles && store.getters.roles.length > 0;
      console.log('hasToken2', hasToken);
      // store.commit("SET_LOGINTOKEN", hasToken);
      // 有token，直接登录
      if (hasToken) {
        if (hasRoles) {
          next();
        } else {
          try {
            const roles = await store.dispatch("user/getUserInfo");
            const accessRoutes = await store.dispatch("permission/generateRoutes", roles);
            router.addRoutes(accessRoutes);
            if (roles == "noOpen") {
              Message.error("您还没加入云木屋代理，正在为您跳转");
              setTimeout(() => {
                window.location.href = process.env.VUE_APP_BASE_MEMBER + "/member/agent/agent";
              }, 1000);
            } else {
              next({ ...to, replace: true });
            }
          } catch (error) {
            next();
          }
        }
      } else {
        // 没有token，去往登录
        // console.log('去登录', process.env.VUE_APP_BASE_SSO + '/sso/login/index?redirectUri=' + encodeURIComponent(window.location.href) + '&token_type=url');
        window.location.href = process.env.VUE_APP_BASE_SSO + '/sso/login/index?redirectUri=' + encodeURIComponent(window.location.href) + '&token_type=url';
      }
    }
  }
});

router.afterEach(() => {
  // 完成进度条
  NProgress.done();
});
